#include "user_persistence.h"
#include <fstream>
#include <sstream>
#include <iostream>

UserFileManager::UserFileManager(const std::string& filename) : filename(filename) {}

std::vector<User*> UserFileManager::loadUsers() {
    std::vector<User*> users;
    std::ifstream file(filename);
    if (file.is_open()) {
        std::string line;
        while (std::getline(file, line)) {
            size_t pos = line.find(',');
            std::string type = line.substr(0, pos);
            line = line.substr(pos + 1);

            pos = line.find(',');
            int id = std::stoi(line.substr(0, pos));
            line = line.substr(pos + 1);

            pos = line.find(',');
            std::string name = line.substr(0, pos);
            line = line.substr(pos + 1);

            pos = line.find(',');
            std::string password = line.substr(0, pos);

            if (type == "RegularCustomer") {
                users.push_back(new RegularCustomer(id, name, password));
            } else if (type == "VIPCustomer") {
                users.push_back(new VIPCustomer(id, name, password));
            } else if (type == "Admin") {
                users.push_back(new Admin(id, name, password));
            } else if (type == "RentalStaff") {
                users.push_back(new RentalStaff(id, name, password));
            } else {
                std::cerr << "Invalid user type: " << type << ". Skipping..." << std::endl;
            }
        }
        file.close();
    } else {
        std::cerr << "Unable to open file for reading." << std::endl;
    }
    return users;
}

void UserFileManager::saveUsers(const std::vector<User*>& users) {
    std::ofstream file(filename);
    if (file.is_open()) {
        for (const auto& user : users) {
            file << user->getType() << "," << user->serialize() << std::endl;
        }
        file.close();
    } else {
        std::cerr << "Unable to open file for writing." << std::endl;
    }
}